﻿namespace Blaze.Editor.CLI
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Text;
    using Debug = UnityEngine.Debug;

    /// <summary>
    /// 提供adb.exe的调用。
    /// </summary>
    public static class Adb
    {
        /// <summary>
        /// adb.exe的路径。
        /// </summary>
        public static string ExecutablePath { get; set; }

        static Adb()
        {
            try
            {
                var query = from path in Environment.GetEnvironmentVariable("Path").Split(';')
                    let target = Path.Combine(path, "adb.exe")
                    where File.Exists(target)
                    select target;
                ExecutablePath = query.FirstOrDefault();
            }
            catch
            {
                ExecutablePath = null;
            }
        }

        /// <summary>
        /// 连接指定地址的设备。
        /// </summary>
        /// <param name="address">地址</param>
        public static void Connect(string address)
        {
            var result = execute(string.Format("connect {0}", address));
            Debug.Log(result);
        }

        /// <summary>
        /// 安装apk包到设备。
        /// </summary>
        /// <param name="path">apk安装包的完整路径</param>
        public static void Install(string path)
        {
            var result = execute(string.Format("install {0}", path));
            Debug.Log(result);
        }

        /// <summary>
        /// 复制文件/目录到设备。
        /// </summary>
        /// <param name="src">源路径</param>
        /// <param name="dest">目标路径</param>
        public static void Push(string src, string dest)
        {
            var result = execute(string.Format("push {0} {1}", src, dest));
            Debug.Log(result);
        }

        private static string execute(string arguments)
        {
            var process = new Process();
            process.StartInfo.FileName = ExecutablePath;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            var success = process.Start();
            if (!success)
                throw new Exception("run adb failed -> arguments=" + arguments);
            var result = process.StandardOutput.ReadToEnd();
            return execute(result);
        }
    }
}